package com.ple.app.map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISDynamicMapServiceLayer;
import com.esri.android.map.ags.ArcGISFeatureLayer;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnLongPressListener;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.map.FeatureSet;
import com.esri.core.map.Graphic;
import com.esri.core.renderer.Renderer;
import com.esri.core.renderer.SimpleRenderer;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.tasks.SpatialRelationship;
import com.esri.core.tasks.ags.query.Query;
import com.esri.core.tasks.identify.IdentifyParameters;
import com.esri.core.tasks.identify.IdentifyResult;
import com.esri.core.tasks.identify.IdentifyTask;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
import com.ple.app.jzsf.R;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Created by twenj on 2016/11/18.
 */

public class ChooseAreaActivity extends Activity {

    private Button btnChooseAreaConfirm;
    private TextView txtViewChooseResult;

    private MapView mapView;
    private GraphicsLayer graphicsLayer;

    //地图服务
    private String baseUrl = null;
    private String servicesUrl = null;
    private String tileServiceUrl = null;
    private String targetSdeMapUrl = null;
    private String targetSdeFeatureUrl = null;

    private String targetUrl = null;

    private ArcGISDynamicMapServiceLayer dynamicMapServiceLayer;
    private ArcGISTiledMapServiceLayer tiledMapServiceLayer;
    private ArcGISFeatureLayer featureLayerServices;

    private Point pt;//当前的与地图交互的点
    private IdentifyParameters identifyParameters;
    private QueryParameters queryParameters;
    private Graphic getGraphic;//当前选择的的Graphic

    private String result;//最后的选择结果

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_area);

        btnChooseAreaConfirm = (Button) findViewById(R.id.btn_choose_confirm);
        txtViewChooseResult = (TextView) findViewById(R.id.txtView_chooseResult);

        //服务地址
        baseUrl = "http://192.168.13.99:6080/arcgis/rest/services/";
        //servicesUrl = baseUrl + "china/MapServer";
        //tileServiceUrl = baseUrl + "china/MapServer";
        targetSdeMapUrl = baseUrl + "china/MapServer";
        targetSdeFeatureUrl = baseUrl + "china/FeatureServer/0";

        targetUrl = targetSdeMapUrl.concat("/0");        //查询的图层

        mapView = (MapView) findViewById(R.id.mapView_choose_area);

        //dynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer(servicesUrl);
        //tiledMapServiceLayer = new ArcGISTiledMapServiceLayer(tileServiceUrl);
        featureLayerServices = new ArcGISFeatureLayer(targetSdeFeatureUrl, ArcGISFeatureLayer.MODE.ONDEMAND);

        mapView.addLayer(featureLayerServices);

        //初始化graphicLayer
        graphicsLayer = new GraphicsLayer();
        mapView.addLayer(graphicsLayer);

        //设定查询参数
        //identifyParameters = new IdentifyParameters();
        //identifyParameters.setDPI(98);
        //identifyParameters.setTolerance(20);
        //identifyParameters.setLayers(new int[]{4});
        //identifyParameters.setLayerMode(IdentifyParameters.TOP_MOST_LAYER);

        //其他查询，暂不启用
        mapView.setOnSingleTapListener(new OnSingleTapListener() {
            @Override
            public void onSingleTap(float v, float v1) {
                if (mapView.isLoaded()) {
                    pt = mapView.toMapPoint(v, v1);

                    //设定QueryTask任务参数
                    queryParameters = new QueryParameters();
                    queryParameters.setGeometry(pt);
                    queryParameters.setReturnGeometry(true);
                    queryParameters.setOutSpatialReference(mapView.getSpatialReference());
                    queryParameters.setOutFields(new String[]{"NAME","NAMEEN"});
                    //queryParameters.setWhere("Vocation = 1");
                    queryParameters.setSpatialRelationship(SpatialRelationship.INTERSECTS);
                    //queryParameters.getOutFields();
                    //queryParameters.getObjectIds();

                    //无需设定查询范围

                    MyAsyncQueryTask myAsyncQueryTask = new MyAsyncQueryTask(pt);
                    myAsyncQueryTask.execute(queryParameters);

                }
                return;
            }
        });

        //传回最后选择的结果
        btnChooseAreaConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //此处需要传递相应数据到MapActivity(即选择好的农场地块结果)
                Intent intent = new Intent(ChooseAreaActivity.this, MapActivity.class);
                intent.putExtra("result", result);
                startActivity(intent);
                finish();
            }
        });

    }

    //辅助类  查询 QueryTask 实现
    private class MyAsyncQueryTask extends AsyncTask<QueryParameters, Void, FeatureResult> {
        private QueryTask queryTask;
        private Point anchorPoint;
        private SimpleFillSymbol fillSymbol;

        MyAsyncQueryTask(Point p) {
            anchorPoint = p;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            queryTask = new QueryTask(targetUrl);// Url 地址为 ArcGISFeatureLayer 服务
            fillSymbol = new SimpleFillSymbol(Color.RED);
            fillSymbol.setAlpha(40);
        }

        @Override
        protected FeatureResult doInBackground(QueryParameters... params) {
            FeatureResult featureResult = null;//用于接受查询到的结果
            /**
             * 接收到的params为之前设定好的QueryParameters
             */
            if (params != null && params.length > 0) {
                queryParameters = params[0];
                try {
                    featureResult = queryTask.execute(queryParameters);
                    return featureResult;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(FeatureResult featureResult) {
            //super.onPostExecute(objects);

            graphicsLayer.removeAll();//清空已经选择的图层

            if (featureResult != null && featureResult.featureCount() > 0) {
                for (Object object : featureResult) {
                    Feature feature = (Feature) object;

                    getGraphic = new Graphic(feature.getGeometry(), fillSymbol, feature.getAttributes());
                    graphicsLayer.addGraphic(getGraphic);//因为未初始化graphicLayer，延迟两天，好尴尬  =_=!

                    //result = feature.getAttributeValue("NAME").toString();
                    Map<String,Object> h = feature.getAttributes();
                    /**
                     * 通过map.keySet()获取map<>key值集合(也就是属性字段集合)
                     * map.get(key)用于获取Map<>中的值
                     * result保存地块的id，以便区分地块
                     */
                    result = h.get("NAMEEN").toString();
                    txtViewChooseResult.setText(result);
                }
            }
            return;
        }
    }

    //辅助类，查询  IdentifyTask 实现（暂不使用）
    private class MyAsyncIdentifyTask extends AsyncTask<IdentifyParameters, Void, IdentifyResult[]> {
        private Point anchorPoint;
        private IdentifyTask identifyTask;
        private ProgressDialog progressDialog = null;

        MyAsyncIdentifyTask(Point point) {
            this.anchorPoint = point;
        }

        @Override
        protected void onPreExecute() {
            identifyTask = new IdentifyTask(servicesUrl);//指定识别的图层
            progressDialog = ProgressDialog.show(ChooseAreaActivity.this, "正在操作中...", "", false);
        }

        @Override
        protected IdentifyResult[] doInBackground(IdentifyParameters... params) {
            IdentifyResult[] mResult = null;
            if (params != null && params.length > 0) {
                IdentifyParameters mParas = params[0];
                try {
                    mResult = identifyTask.execute(mParas);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return mResult;
        }

        @Override
        protected void onPostExecute(IdentifyResult[] identifyResults) {
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            Toast.makeText(ChooseAreaActivity.this, identifyResults.length + "", Toast.LENGTH_LONG).show();
            super.onPostExecute(identifyResults);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
